<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
        <el-form-item prop="params.type">
          <el-input
            v-model="queryParams.params.code"
            class="filter-item"
            clearable
            placeholder="字典编码"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item prop="params.value">
          <el-input
            v-model="queryParams.params.value"
            class="filter-item"
            clearable
            placeholder="字段值"
            style="width: 150px;"
          />
        </el-form-item>
        <!-- 按钮 -->
        <el-button
          v-permission="['/sys/dict/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/sys/dict/add']"
          v-waves
          class="filter-item"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="handleOpenDialog('add')"
        >新增
        </el-button>
        <el-button
          v-permission="['/sys/dict/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
      </el-form>
      <div>
        <el-button
          icon="el-icon-back"
          size="small"
          type="warning"
          @click="handleBack"
        >返回
        </el-button>
      </div>
    </div>
    <!-- 数据表格 -->
    <el-table
      v-loading="dataListLoading"
      :data="dataList"
      border
      fit
      highlight-current-row
      size="small"
      style="width: 100%;"
      @sort-change="handleSortChange"
    >
      <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
      <el-table-column align="center" label="字典名称" prop="dictName" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag :key="scope.row.dictName">{{ scope.row.dictName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="字典编码" prop="code" show-overflow-tooltip sortable />
      <el-table-column align="center" label="字段值" prop="value" show-overflow-tooltip sortable />
      <el-table-column align="center" label="显示顺序" prop="sequence" show-overflow-tooltip sortable />
      <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            v-permission="['/sys/dict/update']"
            v-waves
            size="mini"
            type="primary"
            @click="handleOpenDialog('update', scope.row)"
          >编辑
          </el-button>
          <el-button
            v-permission="['/sys/dict/delete']"
            v-waves
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增-编辑对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="保存中"
      width="500px"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        label-position="right"
        label-width="150px"
        size="small"
        style="width: 400px;"
      >
        <el-form-item label="字典编码：" prop="code">
          <el-input v-model="dataForm.code" placeholder="字典编码" />
        </el-form-item>
        <el-form-item label="字典值：" prop="value">
          <el-input v-model="dataForm.value" placeholder="字典值" />
        </el-form-item>
        <el-form-item label="显示顺序：" prop="sequence">
          <el-input v-model="dataForm.sequence" placeholder="显示顺序" type="显示顺序" />
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="dataForm.remark" placeholder="备注" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='add'" size="small" type="primary" @click="handleAdd">确定</el-button>
        <el-button v-else size="small" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { add, del, fetchList, update } from '@/api/system/dictData'

export default {
  name: 'DictData',
  data() {
    return {
      total: 0,
      dataList: [],
      dataListLoading: true,
      dialogFormVisible: false,
      dialogStatus: '',
      dictId: null,
      dialogLoading: false,
      dialogTitleMap: {
        add: '新增',
        update: '编辑'
      },
      // 查询参数对象
      queryParams: {
        page: 1,
        size: 10,
        sortName: 'sequence',
        sortOrder: 'asc',
        params: {
          code: '',
          value: '',
          dictId: null
        }
      },
      dataForm: {
        code: '',
        value: '',
        sequence: '',
        dictId: null,
        remark: ''
      },
      rules: {
        code: [{ required: true, message: '字典编码不能为空', trigger: 'change' }],
        value: [{ required: true, message: '字段值不能为空', trigger: 'change' }]
      }
    }
  },
  mounted() {
    // 传递过来的dictId
    this.queryParams.params.dictId = this.$route.query.dictId
    this.dictId = this.$route.query.dictId
    this.getDataList()
  },
  methods: {
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getDataList()
    },
    // 手动重置表单
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          code: '',
          value: '',
          sequence: '',
          remark: ''
        }
        this.$refs['dataForm'].resetFields()
      }
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.queryParams.page = 1
      this.getDataList()
    },
    getDataList() {
      this.dataListLoading = true
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataListLoading = false
          this.$message.success(res.msg || '获取数据成功')
        })
        .catch(err => {
          console.log(err)
          this.dataListLoading = false
        })
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    handleOpenDialog(type, rowData) {
      // 表单状态为新增/编辑、打开新增/编辑窗口
      this.resetDataForm()
      this.dialogStatus = type
      this.dialogFormVisible = true
      this.dataForm.dictId = this.$route.query.dictId
      if (type === 'update') {
        this.dataForm = JSON.parse(JSON.stringify(rowData))
      }
    },
    handleBack: function() {
      // 返回上级路由并关闭当前路由
      this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
      this.$router.push({ path: '/system/dict' })
    },
    handleAdd() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          add(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '新增成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleUpdate() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          update(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该记录？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData.id)
            .then(res => {
              console.log(res)
              // this.$message.success(res.msg || '删除成功')
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    }
  }
}
</script>
<style scoped>
</style>
